<script lang="ts" setup>
import {
  ElButton,
  ElTabs,
  ElTabPane,
  ElRow,
  ElCol,
  ElImage,
  ElTable,
  ElPagination,
  ElMessageBox,
  ElMessage,
} from "element-plus";
import { reactive, ref, onMounted } from "vue";
import { router } from "#/router";
import { getDroneById, getFlightList, getFlightLog } from "#/api/sys/equipment";
import GaoAmap from "./map.vue";
import { getAirlineById } from "#/api/task/airline";

const activeName = ref("first");
const record = reactive({
  id: "",
  droneName: "",
  droneBrand: "",
  droneModel: "",
  droneSn: "",
  airportImageUrl: "",
  status: "",
  taskCount: "",
  totalTaskTime: "",
  totalTaskDistance: "",
  droneMaintenanceInfo: {
    droneBatteryMaintenanceState: "",
    droneBatteryMaintenanceTimeLeft: "",
    firmwareUpgradeStatus: "",
    firmwareVersion: "",
    lastMaintainTime: "",
    lastMaintainType: "",
    modeCode: "",
    capacityPercent: "",
  },
});
const srcList = ref([]);
const tableData = ref([]);
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);
const drawDefaultRoute = ref([]); //默认航线数据
const form = reactive({
  safetakeoffaltitude: 120, //安全起飞高度
});
const amapVisible = ref(false);

const handleBack = () => {
  router.go(-1);
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

const getTrack = async (id) => {
  const params = {
    flightId: id,
  };
  const { data } = await getFlightLog(params);
  // console.log(data);
  // drawDefaultRoute.value = convertToAllData(data.wayPoints, data.takeOffRefPoint);
  if (data.length > 0) {
    drawDefaultRoute.value = convertToAllData(data);
    // console.log(drawDefaultRoute.value, "drawDefaultRoute.value");
    amapVisible.value = true;
  } else {
    ElMessage({
      message: "暂无轨迹数据",
      type: "warning",
    });
  }
};

let mapRef = ref();
const lookTrack = (row) => {
  getTrack(row.flightId);
  // amapVisible.value = true;
};

const closeMap = () => {
  amapVisible.value = false;
};

// 转换函数：将所有航点合并成一个 point 数组
// const convertToAllData = (waypoints, takeOffRefPoint) => {
//   // 安全检查：确保 waypoints 是数组
//   if (!waypoints || !Array.isArray(waypoints)) {
//     console.warn("convertToAllData: waypoints 不是有效的数组:", waypoints);
//     waypoints = [];
//   }

//   const points = waypoints.map((wp) => [wp.longitude, wp.latitude, wp.height]); // 所有点

//   // 处理起飞点数据 - 优先使用保存的位置信息
//   // let startPoint = [];
//   // if (form.takeoffLongitude && form.takeoffLatitude) {
//   //   // 使用保存的起飞点位置
//   //   startPoint = [
//   //     form.takeoffLongitude,
//   //     form.takeoffLatitude,
//   //     form.safetakeoffaltitude || 120,
//   //   ];
//   // } else if (takeOffRefPoint) {
//   //   // 如果没有保存的位置，使用传入的起飞点
//   //   const coords = takeOffRefPoint
//   //     .split(",")
//   //     .map((coord) => parseFloat(coord.trim()));
//   //   if (coords.length >= 2) {
//   //     // 安全地获取高度，避免 points[0][2] 为空的情况
//   //     const defaultHeight = points.length > 0 ? points[0][2] : 300;
//   //     startPoint = [
//   //       coords[0],
//   //       coords[1],
//   //       form.safetakeoffaltitude || defaultHeight,
//   //     ];
//   //   }
//   // }

//   return [
//     {
//       points: points, // 所有点组成的数组 - 修正字段名
//       startdata: {
//         point: startPoint, // 起始点
//       },
//     },
//   ];
// };

const convertToAllData = (data) => {
  // 安全检查：确保 waypoints 是数组
  if (!data || !Array.isArray(data)) {
    data = [];
  }

  const points = data.map((wp) => [wp.longitude, wp.latitude, wp.height]); // 所有点

  return [
    {
      points: points, // 所有点组成的数组 - 修正字段名
      // startdata: {
      //   point: data[0], // 起始点
      // },
    },
  ];
};

// const getRouteList = async () => {
//   const params = {
//     id: 358,
//   };
//   const { data } = await getAirlineById(params);
//   drawDefaultRoute.value = convertToAllData(
//     data.wayPoints,
//     data.takeOffRefPoint
//   );
// };

const getDetail = async () => {
  const params = {
    id: router.currentRoute.value.query.id,
  };
  const { data } = await getDroneById(params);

  // 使用对象解构和批量赋值优化代码
  const {
    droneName,
    droneBrand,
    droneModel,
    droneSn,
    imageUrl,
    status,
    taskCount,
    totalTaskTime,
    totalTaskDistance,
    droneMaintenanceInfo,
  } = data;

  // 批量赋值
  Object.assign(record, {
    droneName,
    droneBrand,
    droneModel,
    droneSn,
    airportImageUrl: imageUrl,
    status,
    taskCount,
    totalTaskTime,
    totalTaskDistance,
    // 处理 droneMaintenanceInfo，确保它不会是 null
    droneMaintenanceInfo: droneMaintenanceInfo || {
      lastMaintainTime: "--",
      modeCode: "--",
      firmwareVersion: "--",
      lastMaintainType: "--",
      droneBatteryMaintenanceState: "--",
      firmwareUpgradeStatus: "--",
      droneBatteryMaintenanceTimeLeft: "--",
      capacityPercent: "--",
    },
  });

  srcList.value = [imageUrl];
};

const getList = async () => {
  const params = {
    droneId: router.currentRoute.value.query.id,
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  };
  const { data } = await getFlightList(params);
  tableData.value = data.records;
  total.value = data.total;
};

const handleUpgrade = async (item) => {
  try {
    await ElMessageBox.confirm(
      `是否升级固件版本至【${item.droneName}】吗？`,
      "提示",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        dangerouslyUseHTMLString: true, // 启用HTML内容渲染
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              // await deleteDrone(row.id);
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success("操作成功");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`操作失败: ${error.message || "未知错误"}`);
      console.error("操作无人机失败:", error);
    }
  }
};

const Upgrading = async () => {
  try {
    await ElMessageBox.confirm(`升级中`, {
      type: "warning",
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      beforeClose: async (action, instance, done) => {
        if (action === "confirm") {
          instance.confirmButtonLoading = true;
          try {
            done();
          } catch (error) {
            instance.confirmButtonLoading = false;
          }
        } else {
          done();
        }
      },
    });
    // ElMessage.success("操作成功");
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`操作失败: ${error.message || "未知错误"}`);
      console.error("操作无人机失败:", error);
    }
  }
};

onMounted(() => {
  getDetail();
  // 获取航线
  // getRouteList();
  // 飞行日志
  getList();
});
</script>

<template>
  <div class="detailPage mg-10 pd-20">
    <div class="backBtn">
      <Back width="18px" hight="18px" />
      <ElButton class="btn" @click="handleBack()">返回</ElButton>
    </div>
    <ElTabs v-model="activeName" class="demo-tabs">
      <ElTabPane label="无人机详情" name="first">
        <div class="page">
          <p class="title">无人机信息</p>
          <ElRow>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">无人机名称：</span>
                  <span class="bold">{{ record.droneName }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <span class="labelText">无人机品牌：</span>
                <span class="bold">{{ record.droneBrand }}</span>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <span class="labelText">无人机型号：</span>
                <span class="bold">{{ record.droneModel }}</span>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <span class="labelText">无人机序列：</span>
                <span class="bold">{{ record.droneSn }}</span>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">无人机图片：</span>
                  <ElImage
                    style="width: 60px; height: 60px"
                    :src="record.airportImageUrl"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="srcList"
                    show-progress
                    :initial-index="4"
                    fit="cover"
                  />
                </p>
              </div>
            </ElCol>
          </ElRow>
          <p class="title">运行信息</p>
          <ElRow>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">无人机状态：</span>
                  <span style="color: #67c23a">{{ record.status }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <span class="labelText">累计任务次数：</span>
                <span class="bold">{{ record.taskCount }}次</span>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <span class="labelText">累计任务时间：</span>
                <span class="bold">{{ record.totalTaskTime }}</span>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <span class="labelText">累计任务距离：</span>
                <span class="bold">{{ record.totalTaskDistance }}米</span>
              </div>
            </ElCol>
          </ElRow>
          <h3 class="title">保养信息</h3>
          <ElRow>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">上次保养时间：</span>
                  <span class="bold">{{
                    record.droneMaintenanceInfo.lastMaintainTime
                  }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">机场任务状态：</span>
                  <!-- "0":"空闲中","1":"现场调试","2":"远程调试","3":"固件升级中","4":"作业中","5":"待标定" -->
                  <span
                    class="bold"
                    v-if="record.droneMaintenanceInfo.modeCode == 0"
                    >空闲中</span
                  >
                  <span
                    class="bold"
                    v-if="record.droneMaintenanceInfo.modeCode == 1"
                    >现场调试</span
                  >
                  <span
                    class="bold"
                    v-if="record.droneMaintenanceInfo.modeCode == 2"
                    >远程调试</span
                  >
                  <span
                    class="bold"
                    v-if="record.droneMaintenanceInfo.modeCode == 3"
                    >固件升级中</span
                  >
                  <span
                    class="bold"
                    v-if="record.droneMaintenanceInfo.modeCode == 4"
                    >作业中</span
                  >
                  <span
                    class="bold"
                    v-if="record.droneMaintenanceInfo.modeCode == 5"
                    >待标定</span
                  >
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">固件版本：</span>
                  <span class="bold">{{
                    record.droneMaintenanceInfo.firmwareVersion
                  }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">上次保养类型：</span>
                  <!-- "1":"飞行器基础保养","2":"飞行器常规保养","3":"飞行器深度保养" -->
                  <span
                    class="bold"
                    v-if="record.droneMaintenanceInfo.lastMaintainType == 1"
                    >飞行器基础保养</span
                  >
                  <span
                    class="bold"
                    v-if="record.droneMaintenanceInfo.lastMaintainType == 2"
                    >飞行器常规保养</span
                  >
                  <span
                    class="bold"
                    v-if="record.droneMaintenanceInfo.lastMaintainType == 3"
                    >飞行器深度保养</span
                  >
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">电池保养信息：</span>
                  <!-- "0":"无需保养","1":"待保养","2":"正在保养" -->
                  <span
                    class="bold"
                    v-if="
                      record.droneMaintenanceInfo
                        .droneBatteryMaintenanceState == 0
                    "
                  >
                    无需保养
                  </span>
                  <span
                    class="bold"
                    v-if="
                      record.droneMaintenanceInfo
                        .droneBatteryMaintenanceState == 1
                    "
                  >
                    待保养
                  </span>
                  <span
                    class="bold"
                    v-if="
                      record.droneMaintenanceInfo
                        .droneBatteryMaintenanceState == 2
                    "
                  >
                    正在保养
                  </span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">固件升级状态：</span>
                  <!-- "0":"未升级","1":"升级中" -->
                  <span
                    v-if="
                      record.droneMaintenanceInfo.firmwareUpgradeStatus == 1
                    "
                    class="bold firmware-status"
                    style="color: #f56c6c; cursor: pointer"
                    @click="handleUpgrade(record)"
                    >未升级<i class="triangle-up"> </i
                  ></span>
                  <span
                    v-if="
                      record.droneMaintenanceInfo.firmwareUpgradeStatus == 0
                    "
                    class="bold"
                    style="color: var(--el-color-primary); cursor: pointer"
                    @click="Upgrading(record)"
                    >升级中<i class="triangle-up blue"> </i
                  ></span>
                  <!-- <span
                    class="bold"
                    style="color: #67c23a; cursor: pointer"
                    v-if="
                      record.droneMaintenanceInfo.firmwareUpgradeStatus == 3
                    "
                    >最新版本<i class="triangle-up green"></i
                  ></span> -->
                </p>
              </div>
            </ElCol>
            <!-- <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">下次保养剩余天数：</span>
                  <span class="bold">{{record.maintenanceTimeLeft}}天</span>
                </p>
              </div>
            </ElCol> -->
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">电池保养剩余时间：</span>
                  <span class="bold">{{
                    record.droneMaintenanceInfo.droneBatteryMaintenanceTimeLeft
                  }}</span>
                </p>
              </div>
            </ElCol>
            <ElCol :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="searchCol">
              <div>
                <p class="pText">
                  <span class="labelText">电池电量：</span>
                  <span class="bold">{{
                    record.droneMaintenanceInfo.capacityPercent

                  }}%</span>
                </p>
              </div>
            </ElCol>
          </ElRow>
          <h3 class="title">飞行日志</h3>
          <ElTable :data="tableData" stripe style="width: 100%" row-key="id">
            <ElTable.TableColumn prop="id" label="飞行编号" align="center" />
            <ElTable.TableColumn
              prop="planName"
              label="计划名称"
              align="center"
            />
            <ElTable.TableColumn
              prop="startTime"
              label="起飞时间"
              align="center"
            />
            <ElTable.TableColumn
              prop="airportName"
              label="飞行轨迹"
              align="center"
            >
              <template #default="scope">
                <ElButton
                  link
                  type="primary"
                  size="small"
                  @click="lookTrack(scope.row)"
                  >查看</ElButton
                >
              </template>
            </ElTable.TableColumn>
            <ElTable.TableColumn
              prop="endTime"
              label="降落时间"
              align="center"
            />
            <ElTable.TableColumn
              prop="airline"
              label="航线名称"
              align="center"
            />
            <ElTable.TableColumn
              prop="airportOrPilot"
              label="执行飞手/机场"
              align="center"
            />
            <ElTable.TableColumn prop="status" label="任务进度" align="center">
              <template #default="scope">
                <span v-if="scope.row.status === 0">未开始</span>
                <span
                  v-else-if="scope.row.status === 1"
                  style="color: var(--el-color-primary)"
                  >进行中</span
                >
                <span v-else-if="scope.row.status === 4" style="color: #67c23a"
                  >已完成</span
                >
                <span v-else-if="scope.row.status === 3" style="color: #f56c6c"
                  >已取消</span
                >
                <span v-else>{{ scope.row.status }}</span>
              </template>
            </ElTable.TableColumn>
          </ElTable>
          <div class="pagination">
            <ElPagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 80, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </ElTabPane>
    </ElTabs>
    <GaoAmap
      ref="mapRef"
      v-model:isShow="amapVisible"
      :drawDefaultRoute="drawDefaultRoute"
      @close="closeMap"
    ></GaoAmap>
  </div>
</template>

<style scoped>
p {
  font-weight: 900;
}

.title {
  padding: 8px 10px;
  margin-bottom: 16px;
  font-size: 14px;
  background: #f5f7fa;
}

.el-col {
  margin-bottom: 20px;
}

.firmware-status {
  position: relative;
}

.triangle-up {
  display: inline-block;
  width: 0;
  height: 0;
  margin-left: 0px;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 16px solid #f56c6c;
  vertical-align: middle;
}

.blue {
  border-bottom: 16px solid var(--el-color-primary);
}

.green {
  border-bottom: 16px solid #67c23a;
}

.labelText {
  color: #909399;
}

.searchCol {
  font-size: 14px;
  color: #303133;
}

.pText {
  font-weight: 400;
  text-indent: 10px;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px 24px 0px 16px;
}

/* .map {
  width: 760px;
  height: 700px;
  display: flex;
} */
</style>